/**
 * 
 */
package cn.gov.msa.service.impl;

import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.UsesSunHttpServer;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;

import cn.gov.msa.collection.LdapService;
import cn.gov.msa.collection.WxService;
import cn.gov.msa.dao.ApplyMapper;
import cn.gov.msa.dao.AuditAnnexMapper;
import cn.gov.msa.dao.AuditOpinionMapper;
import cn.gov.msa.dao.DeclareItemMapper;
import cn.gov.msa.dao.FlowBusinessMapper;
import cn.gov.msa.dao.FlowInstanceMapper;
import cn.gov.msa.dao.FlowMapper;
import cn.gov.msa.dao.FlowNextNodeMapper;
import cn.gov.msa.dao.FlowNodeMapper;
import cn.gov.msa.dao.FlowNodeParamMapper;
import cn.gov.msa.dao.FlowTaskMapper;
import cn.gov.msa.dao.FlowTaskUserMapper;
import cn.gov.msa.dao.MessageLogBakMapper;
import cn.gov.msa.dao.OrgMapper;
import cn.gov.msa.dao.RecordCompanyMapper;
import cn.gov.msa.dao.UserDetailMapper;
import cn.gov.msa.model.Apply;
import cn.gov.msa.model.AuditAnnex;
import cn.gov.msa.model.AuditOpinion;
import cn.gov.msa.model.DeclareItem;
import cn.gov.msa.model.Flow;
import cn.gov.msa.model.FlowBusiness;
import cn.gov.msa.model.FlowInstance;
import cn.gov.msa.model.FlowNextNode;
import cn.gov.msa.model.FlowNextNodeE;
import cn.gov.msa.model.FlowNode;
import cn.gov.msa.model.FlowNodeParam;
import cn.gov.msa.model.FlowTask;
import cn.gov.msa.model.FlowTaskUser;
import cn.gov.msa.model.MessageLog;
import cn.gov.msa.model.RecordCompany;
import cn.gov.msa.model.UserRole;
import cn.gov.msa.pagehelper.CustomPageHelper;
import cn.gov.msa.service.FlowService;
import cn.gov.msa.service.TaskService;
import cn.gov.msa.util.MultiTaskService;
import cn.gov.msa.util.PropertiesTools;
import cn.gov.msa.util.WebServiceTools;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**   
* @Title: FlowServiceImpl.java 
* @Package cn.gov.msa.service.impl 
* @Description: TODO(用一句话描述该文件做什么) 
* @author 何宇江  
* @date 2018年2月8日 下午4:44:29 
*/

public class FlowServiceImpl implements FlowService {
	private Logger logger = Logger.getLogger(FlowServiceImpl.class);

	@Autowired
	FlowMapper flowMapper;
	@Autowired
	FlowNodeMapper flowNodeMapper;
	@Autowired
	FlowNextNodeMapper flowNextNodeMapper;
	@Autowired
	FlowBusinessMapper flowBusinessMapper;
	@Autowired
	FlowNodeParamMapper flowNodeParamMapper;
	@Autowired
	UserDetailMapper userDetailMapper;
	@Autowired
	AuditAnnexMapper auditAnnexMapper;
	@Autowired
	RecordCompanyMapper recordCompanyMapper;
	@Autowired
	TaskService taskService;
	@Autowired
	AuditOpinionMapper auditOpinionMapper;
	@Autowired
	ApplyMapper applyMapper;
	@Autowired 
	FlowInstanceMapper flowInstanceMapper;
	@Autowired 
	FlowTaskMapper flowTaskMapper;
	@Autowired 
	FlowTaskUserMapper flowTaskUserMapper;
	@Autowired
	OrgMapper orgMapper;
	@Autowired
	MessageLogBakMapper messageLogBakMapper;
	
	private static String cmpUrl = PropertiesTools.readProperties("project.url");
	private static String cspUrl = PropertiesTools.readProperties("project.csp.url");
	private static String wsUrl = PropertiesTools.readProperties("gahWS.url");
	private static String appUrl = PropertiesTools.readProperties("project.app.url");
	
	@Override
	public List<Flow> selectData(int currentPage, int pageRecord, Flow flow) throws Exception {
		

		CustomPageHelper.startPage(currentPage, pageRecord); // 核心分页代码
        
        //读取数据库信息
	    List<Flow> flowList = flowMapper.selectData(flow);

	    return flowList;
	}

	@Override
	public Flow getInfoByID(String id) throws Exception {
		return null;
	}

	@Override
	@Transactional
	public boolean save(Flow flow, List<FlowNode> flowNodeList, List<FlowNextNode> flowNextNodeList) throws Exception {
		boolean result = false;
		
		int i = flowMapper.insert(flow);
		
		if (flowNodeList != null) {
			for (FlowNode flowNode : flowNodeList) {
				flowNodeMapper.insert(flowNode);
			}
		}
		

		if (flowNextNodeList != null) {
			for (FlowNextNode flowNextNode : flowNextNodeList) {
				flowNextNodeMapper.insert(flowNextNode);
			}
		}
		
		result = i > 0 ? true : false;
		
		return result;
	}

	@Override
	public boolean updateData(Flow flow, List<FlowNode> flowNodeList, List<FlowNextNode> flowNextNodeList)
			throws Exception {
		return false;
	}

	@Override
	@Transactional
	public boolean delete(String id) throws Exception {
		boolean result = false;
		
		FlowNode flowNode = new FlowNode();
		flowNode.setFlownumber(id);		
		List<FlowNode> flowNodeList = flowNodeMapper.selectData(flowNode);
		for (FlowNode flowNode2 : flowNodeList) {
			String nodecode = flowNode2.getNodecode();
			flowNextNodeMapper.deleteByNodecode(nodecode);
		}
		
		flowNodeMapper.deleteByFlownumber(id);
		
		int i = flowMapper.deleteByPrimaryKey(id);

		result = i > 0 ? true : false;
		
		return result;
	}

	@Override
	public List<FlowNode> getNodes(String id) throws Exception {
		List<FlowNode> flowNodeList = null; 
		
		FlowNode flowNode = new FlowNode();
		flowNode.setFlownumber(id);
		
		flowNodeList = flowNodeMapper.selectData(flowNode);
		
		return flowNodeList;
	}

	@Override
	public List<FlowNextNodeE> getNextNodes(String nodecode) throws Exception {
		List<FlowNextNodeE> flowNextNodeEList = null; 
		
		FlowNextNodeE flowNextNodeE = new FlowNextNodeE();
		flowNextNodeE.setNodecode(nodecode);
		
		flowNextNodeEList = flowNextNodeMapper.selectData(flowNextNodeE);
		
		return flowNextNodeEList;
	}

	@Override
	@Transactional
	public boolean saveNextNode(String nodecode, List<FlowNextNode> flowNextNodeList) throws Exception {
		boolean result = false;
		int j = 0;
		
		int i = flowNextNodeMapper.deleteByNodecode(nodecode);
		for (FlowNextNode flowNextNode : flowNextNodeList) {
			j = flowNextNodeMapper.insert(flowNextNode);
		}
		
		if(j > 0)
			result = true;
		
		return result;
	}

	@Override
	public boolean saveNextNode(JSONObject param) {
		boolean result = false;
		int j = 0;

    	JSONArray jaParam = param.getJSONArray("datas");
    	for (Object object : jaParam) {
			JSONObject json = JSONObject.fromObject(object);
			String nodecode = json.getString("nodecode");
			String nextnodecodes = json.getString("nextnodecode");
			
			List<FlowNextNode> flowNextNodeList = new ArrayList<FlowNextNode>();
			for (int i = 0; i < nextnodecodes.split(",").length; i++) {
				FlowNextNode flowNextNode = new FlowNextNode();
				flowNextNode.setNodecode(nodecode);
				flowNextNode.setNextnodecode(nextnodecodes.split(",")[i]);
				flowNextNode.setSerialnumber(i + 1);
				flowNextNodeList.add(flowNextNode);
			}
			
			if(flowNextNodeList != null){
				int i = flowNextNodeMapper.deleteByNodecode(nodecode);
				for (FlowNextNode flowNextNode : flowNextNodeList) {
					j = flowNextNodeMapper.insert(flowNextNode);
				}
			}
		}
    	
		if(j > 0)
			result = true;
		
		return result;
	}
	
	@Autowired
	DeclareItemMapper declareItemMapper;
	
	@Override
	@Transactional
	public boolean saveFlowBusiness(FlowBusiness flowBusiness, List<FlowNodeParam> flowNodeParamList) throws Exception{
	boolean result = false;
		
		int i = flowBusinessMapper.insert(flowBusiness);
		
		if (flowNodeParamList != null) {
			for (FlowNodeParam flowNodeParam : flowNodeParamList) {
				flowNodeParamMapper.insert(flowNodeParam);
			}
		}
		
		result = i > 0 ? true : false;
		
		return result;
		
	}
	
	
	
	@Override
	@Transactional
	public String startFlow(String flownumber, String businessid, String businessnumber, String nodecode, String orgcode, String senduserid, String sendusername,String itemno,String applyno,String itemname,String orgname) throws Exception{
		String result = "";
		LdapService ldapService = new LdapService();
		
		boolean isUpdate = false;
		List<FlowTaskUser> fourATaskUserList =new ArrayList<FlowTaskUser>();

		String instanceid = "";
		FlowInstance flowInstanceIsExist = flowInstanceMapper.selectByBusinessId(businessid);
		if(null != flowInstanceIsExist && "" != flowInstanceIsExist.getInstanceid() && null != flowInstanceIsExist.getInstanceid()){
			instanceid = flowInstanceIsExist.getInstanceid();
			isUpdate = true;
		}
		else
			instanceid = UUID.randomUUID().toString().toUpperCase();
		
		String flowtaskid = "";
		String currentNodeId="";
		String currentNodeName="";
//		保存流程任务
		List<FlowNodeParam> flowNodeParamList = flowNodeParamMapper.selectByBusinessnumber(businessnumber);
		List<FlowTask> flowTaskList = new ArrayList<FlowTask>(); 
		for (FlowNodeParam flowNodeParam : flowNodeParamList) {
			String taskid = UUID.randomUUID().toString().toUpperCase();
			
			FlowTask flowTask = new FlowTask();
			flowTask.setTaskid(taskid);
			flowTask.setInstanceid(instanceid);
			flowTask.setSerialnumber(Integer.parseInt(flowNodeParam.getSerialnumber().toString()));
			flowTask.setNodecode(flowNodeParam.getNodecode());
			flowTask.setTaskname(flowNodeParam.getNodename());
			
//			申报用户
			FlowNode flowNodeFist = getFistNode(flownumber);
			
			if(flowNodeFist != null && flowNodeParam.getNodecode().toString().equals(flowNodeFist.getNodecode())){
				flowTask.setSenduserid(senduserid);
				flowTask.setSendusername(sendusername);

				FlowTaskUser flowTaskUser = new FlowTaskUser();
				flowTaskUser.setSerialnumber(1); 
				flowTaskUser.setTaskid(taskid);
				flowTaskUser.setUserid(senduserid);
				flowTaskUser.setUsername(sendusername);
				int iTaskUser = flowTaskUserMapper.insert(flowTaskUser);
			}
//			申报用户
			
//			受理用户
			if(flowNodeParam.getNodecode().toString().equals(nodecode)){
				flowtaskid = taskid;    //设置实例表的当前任务ID
				currentNodeId=flowNodeParam.getNodecode();
				currentNodeName=flowNodeParam.getNodename();
				flowTask.setSenduserid(senduserid);
				flowTask.setSendusername(sendusername);
				
				int iUser = 1;
				String rolecodes = flowNodeParam.getRolecode();
				for (String rolecode : rolecodes.split(",")) {
					logger.info("受理角色："+rolecode+":受理机构:"+orgcode);
					JSONArray jaUser = new JSONArray();
					
					if("1".equals(PropertiesTools.readProperties("sys.isintegration"))){
						jaUser = LdapService.getUserByRoleCode(rolecode,orgMapper.select4aByOrgCode(orgcode).getOrgCode4A());   //在ldap接口获取用户
						logger.info("受理用户列表："+jaUser);
					}
					else{
						UserRole userRole = new UserRole();
						userRole.setRolecode(rolecode);
						userRole.setOrgcode(orgcode);
						jaUser = JSONArray.fromObject(userDetailMapper.selectUserRole(userRole));
					}
					
					for (Object user : jaUser) {
						JSONObject jsonUser = JSONObject.fromObject(user);
						logger.info("受理用户："+jsonUser);
						FlowTaskUser flowTaskUser = new FlowTaskUser();
						flowTaskUser.setSerialnumber(iUser); iUser++;
						flowTaskUser.setTaskid(taskid);
						flowTaskUser.setUserid(jsonUser.getString("userid"));
						flowTaskUser.setUsername(jsonUser.getString("username"));
						int iTaskUser = flowTaskUserMapper.insert(flowTaskUser);
						fourATaskUserList.add(flowTaskUser);
					}
				}
			}
//			受理用户
			int iTask = flowTaskMapper.insert(flowTask);
		}

		FlowInstance flowInstance = new FlowInstance();
		flowInstance.setInstanceid(instanceid);
		flowInstance.setFlownumber(flownumber);
		flowInstance.setBusinessid(businessid);
		flowInstance.setFlowtaskid(flowtaskid);
		
//		保存流程实例
		int i = 0;
		if(isUpdate)
			i = flowInstanceMapper.updateByPrimaryKey(flowInstance);
		else
			i = flowInstanceMapper.insert(flowInstance);
		
		
		//4A任务
//		try{
//			JSONArray gTasks=new JSONArray();
//			System.out.println("4A任务指派:");
//			for (int j = 0; j < fourATaskUserList.size(); j++) {
//				JSONObject gTask=new JSONObject();
//				gTask.put("userId", fourATaskUserList.get(j).getUserid());
//				gTask.put("appId", PropertiesTools.readProperties("project.appId"));
//				gTask.put("appName", PropertiesTools.readProperties("project.appName"));
//				gTask.put("status", currentNodeId);
//				gTask.put("statusName", currentNodeName);
//				gTask.put("currentNodeId", currentNodeId);
//				gTask.put("currentNodeName", currentNodeName);
//				gTask.put("appTaskId", fourATaskUserList.get(j).getTaskuserid());//taskUserId作为4A中的taskId
//				gTask.put("taskName", applyno+"-"+itemname+"-"+currentNodeName);
//				String urlSuffix= URLEncoder.encode("applyid="+businessid+"&applyno="+applyno+"&instanceid="+instanceid+"&flowtaskid="+flowtaskid+"&taskuserid="+fourATaskUserList.get(j).getTaskuserid()+"&itemname="+itemname+"&taskname="+currentNodeName+"&orgname="+orgname,"UTF-8");
//				gTask.put("taskURL",cmpUrl+"/backstage/approval/business/accept4a.html?"+urlSuffix);
//				gTask.put("isDone", "0");
//				gTask.put("accessPlatform", "1");// accessPlatform 0：移动端  1：PC端
//				gTask.put("businessType", PropertiesTools.readProperties("project.businessType"));
//				gTask.put("createDate",cn.gov.msa.util.DateUtils.getNow());
//				gTasks.add(gTask);
//				//移动端
//				gTask.put("appTaskId", "A"+fourATaskUserList.get(j).getTaskuserid());//taskUserId作为4A中的taskId
//				gTask.put("taskURL", appUrl+"html/auditor.html?applyno="+applyno);
//				gTask.put("accessPlatform", "0");
//				gTasks.add(gTask);
//			}
//			System.out.println(gTasks);
//			System.out.println(taskService.gTaskBatchAdd(gTasks));
//	
//			JSONObject cspTask=new JSONObject();
//			cspTask.put("userId", senduserid);
//			cspTask.put("appId", PropertiesTools.readProperties("project.csp.appId"));
//			cspTask.put("appName",  PropertiesTools.readProperties("project.csp.appName"));
//			cspTask.put("status", currentNodeId);
//			cspTask.put("statusName", "待受理");
//			cspTask.put("currentNodeId", currentNodeId);
//			cspTask.put("currentNodeName", currentNodeName);
//			cspTask.put("appTaskId", applyno);//applyno作为taskId
//			cspTask.put("taskName", itemname);
//			cspTask.put("createDate",cn.gov.msa.util.DateUtils.getNow());
//			if(itemno.equals("10001")) {
//				cspTask.put("taskURL", cspUrl+"/business/recordDetail.html?applyno="+applyno+"&itemno="+itemno);
//			}else {
//				cspTask.put("taskURL", cspUrl+"/business/detail.html?applyno="+applyno+"&itemno="+itemno);
//			}
//			cspTask.put("isDone", "1");
//			cspTask.put("accessPlatform", "0");
//			cspTask.put("businessType", PropertiesTools.readProperties("project.businessType"));
//			System.out.println("综合任务："+cspTask);
//			System.out.println(WebServiceTools.getDataByUrl(wsUrl, "gTasksUpdateOrAdd", cspTask.toString()));
//		}
//		catch(Exception e){
//			System.err.println("门户待办集成代码块报错！");
//		}
		
		if(i > 0)
			result = instanceid;
		
		return result;
	}

	

	@Transactional
	public boolean saveAuditOpinion(AuditOpinion auditOpinion, List<FlowTaskUser> flowTaskUserList,JSONArray annexids,FlowNode nextflownode,String taskuserid,String itemno,String applyno,String proposerid,String itemname,String orgname) throws Exception{

		boolean result = false;
		
//		通过业务ID、下一节点，查询下一步任务的taskid,并更新实例表的taskid
		FlowInstance flowInstance = flowInstanceMapper.selectByPrimaryKey(auditOpinion.getInstanceid());   //业务ID，获取流程实例
		
		FlowTask flowTask = new FlowTask();
		flowTask.setInstanceid(flowInstance.getInstanceid());
		List<FlowTask> flowTaskList = flowTaskMapper.selectData(flowTask);
		
		String nexttaskid = "";  //获取下一节点的taskid
		String taskid = "";  //获取当前节点的taskid
		for (FlowTask flowTask2 : flowTaskList) {
			if(flowTask2.getNodecode().equals(auditOpinion.getNextnodecode())){
				nexttaskid = flowTask2.getTaskid();
			}
			else if(flowTask2.getNodecode().equals(auditOpinion.getNodecode())){
				taskid = flowTask2.getTaskid();
			}
		}
		JSONObject param=new JSONObject();
		param.put("taskid", taskid);
		List <FlowTaskUser> oldFlowTaskUser=flowTaskUserMapper.selectByParam(param);
		JSONArray gTasksDeleteByAppIds=new JSONArray();
		for (int i = 0; i < oldFlowTaskUser.size(); i++) {
			if(taskuserid.equals(oldFlowTaskUser.get(i).getTaskuserid())) {
				FlowTaskUser record=new FlowTaskUser();
				record.setTaskuserid(oldFlowTaskUser.get(i).getTaskuserid());
				record.setTaskuserstate("1");
				flowTaskUserMapper.updateByPrimaryKeySelective(record);
				
				
//				JSONObject gTask=new JSONObject();
//				gTask.put("userId", oldFlowTaskUser.get(i).getUserid());
//				gTask.put("appId",  PropertiesTools.readProperties("project.appId"));
//				gTask.put("appName",  PropertiesTools.readProperties("project.appName"));
//				gTask.put("status", nextflownode.getNodecode());
//				gTask.put("statusName",nextflownode.getNodename());
//				gTask.put("currentNodeId", nextflownode.getNodecode());
//				gTask.put("currentNodeName", nextflownode.getNodename());
//				gTask.put("appTaskId", oldFlowTaskUser.get(i).getTaskuserid());//taskUserId作为4A中的taskId
//				gTask.put("isDone", "1");
//				System.out.println("4A任务更新");
//				System.out.println(gTask);
//				System.out.println(taskService.gTasksUpdateOrAdd(gTask));
			}else {
				FlowTaskUser record=new FlowTaskUser();
				record.setTaskuserid(oldFlowTaskUser.get(i).getTaskuserid());
				record.setTaskuserstate("2");
				flowTaskUserMapper.updateByPrimaryKeySelective(record);
				
//				JSONObject gTasksDeleteByAppId=new JSONObject();
//				gTasksDeleteByAppId.put("appTaskId", oldFlowTaskUser.get(i).getTaskuserid());
//				gTasksDeleteByAppId.put("appId", PropertiesTools.readProperties("project.appId"));
//				gTasksDeleteByAppIds.add(gTasksDeleteByAppId);
			}
		}
		
//		taskService.gTasksBatchDeleteByAppId(gTasksDeleteByAppIds);
		//更新综合待办状态
//		JSONObject cspTask=new JSONObject();
//		cspTask.put("userId", proposerid);
//		cspTask.put("appId", PropertiesTools.readProperties("project.csp.appId"));
//		cspTask.put("appName",  PropertiesTools.readProperties("project.csp.appName"));
//		cspTask.put("status", nextflownode.getNodecode());
//		if(nextflownode.getNodename().indexOf("办结")>-1||nextflownode.getNodename().indexOf("不予")>-1||nextflownode.getNodename().indexOf("补正")>-1) {
//			cspTask.put("statusName", nextflownode.getNodename());
//		}else if(nextflownode.getNodename().indexOf("受理")>-1){
//			cspTask.put("statusName", "待受理");
//		}else {
//			cspTask.put("statusName", "已受理");
//		}
//		cspTask.put("currentNodeId", nextflownode.getNodecode());
//		cspTask.put("currentNodeName", nextflownode.getNodename());
//		cspTask.put("appTaskId", applyno);//applyno作为taskId
//		cspTask.put("createDate",cn.gov.msa.util.DateUtils.getNow());
//		if(itemno.equals("10001")) {
//			cspTask.put("taskURL", cspUrl+"/business/recordDetail.html?applyno="+applyno+"&itemno="+itemno);
//		}else {
//			cspTask.put("taskURL", cspUrl+"/business/detail.html?applyno="+applyno+"&itemno="+itemno);
//		}
//		cspTask.put("isDone", "1");
//		cspTask.put("accessPlatform", "0");
//		cspTask.put("businessType", PropertiesTools.readProperties("project.businessType"));
//		System.out.println("综合任务："+cspTask);
//		System.out.println(WebServiceTools.getDataByUrl(wsUrl, "gTasksUpdateOrAdd", cspTask.toString()));
	     
		
		

		
		
		flowInstance.setFlowtaskid(nexttaskid);
		int iInstance = flowInstanceMapper.updateByPrimaryKey(flowInstance);
		

//		通过当前taskid，更新任务表的发送时间、发送用户。。。。
		FlowTask record = new FlowTask();
		record.setTaskid(taskid);
//		record.setSenduserid(auditOpinion.getUserid());
//		record.setSendusername(auditOpinion.getUsername());
		record.setTaskstate(1);
		int iTask = flowTaskMapper.updateByPrimaryKey(record);
		
//		通过下一节点的taskid，更新任务表的发送时间、发送用户。。。。
		FlowTask record1 = new FlowTask();
		record1.setTaskid(nexttaskid);
		record1.setSenduserid(auditOpinion.getUserid());
		record1.setSendusername(auditOpinion.getUsername());
		record1.setTaskstate(0);
		int iTask1 = flowTaskMapper.updateByPrimaryKey(record1);
		
		
		//更新业务单流程数据
		Apply apply = applyMapper.selectByPrimaryKey(auditOpinion.getBusinessid());
		if(apply != null){
			FlowNode flownode = flowNodeMapper.selectByPrimaryKey(auditOpinion.getNextnodecode());
			apply.setNodeno(flownode.getNodecode());
			apply.setNodename(flownode.getNodename());
			int iApply = applyMapper.updateByPrimaryKey(apply);
			if("10001".equals(apply.getItemno())) {
				RecordCompany recordCompany= recordCompanyMapper.selectByApplyid(apply.getApplyid());
				recordCompany.setState(flownode.getNodename().indexOf("办结")>-1?(short)1:(short)2);
				recordCompanyMapper.updateByPrimaryKey(recordCompany);
			}
		}
		
		
//		插入任务用户
		int k = 1;
		for (FlowTaskUser flowTaskUser : flowTaskUserList) {
			flowTaskUser.setTaskid(nexttaskid);
			flowTaskUser.setSerialnumber(k);
			flowTaskUserMapper.insert(flowTaskUser);
			k++;
		}
		
//		System.out.println("4A任务指派");
//		for (int j = 0; j < flowTaskUserList.size(); j++) {
//			JSONObject gTask=new JSONObject();
//			gTask.put("userId", flowTaskUserList.get(j).getUserid());
//			gTask.put("appId",  PropertiesTools.readProperties("project.appId"));
//			gTask.put("appName",  PropertiesTools.readProperties("project.appName"));
//			gTask.put("status", nextflownode.getNodecode());
//			gTask.put("statusName",  nextflownode.getNodename());
//			gTask.put("currentNodeId", nextflownode.getNodecode());
//			gTask.put("currentNodeName", nextflownode.getNodename());
//			gTask.put("appTaskId", flowTaskUserList.get(j).getTaskuserid());//taskUserId作为4A中的taskId
//			gTask.put("taskName", applyno+"-"+itemname+"-"+nextflownode.getNodename());
//			String urlSuffix=URLEncoder.encode("applyid="+auditOpinion.getBusinessid()+"&applyno="+applyno+"&instanceid="+auditOpinion.getInstanceid()+"&flowtaskid="+nexttaskid+"&taskuserid="+ flowTaskUserList.get(j).getTaskuserid()+"&itemname="+itemname+"&taskname="+nextflownode.getNodename()+"&orgname="+orgname,"UTF-8");
//			gTask.put("taskURL", cmpUrl+"/backstage/approval/business/accept4a.html?"+urlSuffix);
//			gTask.put("isDone", "0");
//			gTask.put("accessPlatform", "0");
//			gTask.put("businessType", PropertiesTools.readProperties("project.businessType"));
//			System.out.println(gTask);
//			System.out.println(taskService.gTasksUpdateOrAdd(gTask));
//		}
		
		
		
		
//		插入意见
		int i = auditOpinionMapper.insert(auditOpinion);
		if(i>0&&annexids!=null&&!annexids.isEmpty()) {
			for (int j = 0; j < annexids.size(); j++) {
				AuditAnnex auditAnnex=new AuditAnnex();
				auditAnnex.setAnnexid(annexids.getJSONObject(j).optString("annexid"));
				auditAnnex.setOpinionid(auditOpinion.getOpinionid());
				auditAnnexMapper.updateByPrimaryKeySelective(auditAnnex);
			}
		}
		
		result = i > 0 ? true : false;
		
		return result;
	}

	
	@Transactional
	public void saveJointlySignOpinion(AuditOpinion auditOpinion, List<FlowTaskUser> flowTaskUserList,JSONArray annexids,String taskuserid) throws Exception{
	

		FlowInstance flowInstance = flowInstanceMapper.selectByPrimaryKey(auditOpinion.getInstanceid());
		
		FlowTask flowTask = new FlowTask();
		flowTask.setInstanceid(flowInstance.getInstanceid());
		List<FlowTask> flowTaskList = flowTaskMapper.selectData(flowTask);
		
		String nexttaskid = "";  //获取下一节点的taskid
		String taskid = "";  //获取当前节点的taskid
		boolean last=false;
		for (FlowTask flowTask2 : flowTaskList) {
			if(flowTask2.getNodecode().equals(auditOpinion.getNextnodecode())){
				nexttaskid = flowTask2.getTaskid();
				FlowNode flowNode=flowNodeMapper.selectByPrimaryKey(flowTask2.getNodecode());
				String flowNodeMaxNum=flowNodeMapper.selectMaxNumByFlownumber(flowNode.getFlownumber());
				if(flowNodeMaxNum.equals(flowTask2.getSerialnumber().toString())) {
					last=true;
				}
			}
			else if(flowTask2.getNodecode().equals(auditOpinion.getNodecode())){
				taskid = flowTask2.getTaskid();
			}
		}
		
		flowInstance.setFlowtaskid(nexttaskid);
		flowInstanceMapper.updateByPrimaryKey(flowInstance);
		

//		通过当前taskid，更新任务表的发送时间、发送用户。。。。
		FlowTask record = new FlowTask();
		record.setTaskid(taskid);
		record.setTaskstate(1);
		flowTaskMapper.updateByPrimaryKey(record);
		
//		通过下一节点的taskid，更新任务表的发送时间、发送用户。。。。
		FlowTask record1 = new FlowTask();
		record1.setTaskid(nexttaskid);
		record1.setSenduserid(auditOpinion.getUserid());
		record1.setSendusername(auditOpinion.getUsername());
		if(!last) {
			record1.setTaskstate(0);
		}else {
			record1.setTaskstate(1);
		}
		flowTaskMapper.updateByPrimaryKey(record1);

//		插入任务用户
		int k = 1;
		for (FlowTaskUser flowTaskUser : flowTaskUserList) {
			flowTaskUser.setTaskid(nexttaskid);
			flowTaskUser.setSerialnumber(k);
			flowTaskUserMapper.insert(flowTaskUser);
			k++;
		}
	
//		插入意见
		int i = auditOpinionMapper.insert(auditOpinion);
		if(i>0&&annexids!=null&&!annexids.isEmpty()) {
			for (int j = 0; j < annexids.size(); j++) {
				AuditAnnex auditAnnex=new AuditAnnex();
				auditAnnex.setAnnexid(annexids.getJSONObject(j).optString("annexid"));
				auditAnnex.setOpinionid(auditOpinion.getOpinionid());
				auditAnnexMapper.updateByPrimaryKeySelective(auditAnnex);
			}
		}
		FlowTaskUser flowTaskUser=new FlowTaskUser();
		flowTaskUser.setTaskuserid(taskuserid);
		flowTaskUser.setTaskuserstate("1");
		flowTaskUserMapper.updateByPrimaryKeySelective(flowTaskUser);
		
		JSONObject gTask=new JSONObject();
		gTask.put("userId", auditOpinion.getUserid());
		gTask.put("appId",  PropertiesTools.readProperties("project.appId"));
		gTask.put("appName",  PropertiesTools.readProperties("project.appName"));
		gTask.put("appTaskId", taskuserid);//taskUserId作为4A中的taskId
		gTask.put("isDone", "1");
		gTask.put("accessPlatform", "0");
		gTask.put("businessType",  PropertiesTools.readProperties("project.businessType"));
		System.out.println("4A会签任务更新");
		System.out.println(gTask);
		System.out.println(taskService.gTasksUpdateOrAdd(gTask));
	}
	
	
	@Override
	public FlowNode getFistNode(String flownumber) throws Exception {
		
		FlowNode record = new FlowNode();
		record.setFlownumber(flownumber);
		record.setSerialnumber(1);;
		
		List<FlowNode> flowNodeList = flowNodeMapper.selectData(record);
		
		FlowNode flowNode = new FlowNode();
		if(flowNodeList.size() > 0)
			flowNode = flowNodeList.get(0);
		
		return flowNode;
	}

	@Override
	public FlowNode getAcceptNode(String flownumber) throws Exception {
		
		FlowNode flowNode = new FlowNode();
		
		FlowNode flowNodeFirst = getFistNode(flownumber);
		
		if(flowNodeFirst != null){
			FlowNextNodeE record = new FlowNextNodeE();
			record.setNodecode(flowNodeFirst.getNodecode());
			List<FlowNextNodeE> flowNextNodeEList = flowNextNodeMapper.selectData(record);

			FlowNextNodeE flowNextNodeE = new FlowNextNodeE();
			if(flowNextNodeEList.size() > 0){
				flowNextNodeE = flowNextNodeEList.get(0);
				
				String nodecode = flowNextNodeE.getNextnodecode();
				flowNode = flowNodeMapper.selectByPrimaryKey(nodecode);
			}
		}
		
		return flowNode;
	}
}
